package com.ywgt.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JucFactory {

    public static void main(String[] args) {
    B a=new B();
    new Thread(()->{
        for (int i=0;i<10;i++){
            try {
                a.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    },"A").start();

    new Thread(()->{
        for (int i=0;i<10;i++){
            try {
                a.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    },"C").start();

    new Thread(()->{
        for (int i=0;i<10;i++){
            try {
                a.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    },"B").start();

    new Thread(()->{
        for (int i=0;i<10;i++){
            try {
                a.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    },"D").start();
}
}

class B {

    Lock lock = new ReentrantLock();
    private int i = 0;
    Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {

        lock.lock();
        try {
            while (i != 0) {
                //等待
                condition.await();
            }
            i++;
            //完成，通知其他线程
            System.out.println(Thread.currentThread().getName() + i);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (i== 0) {
                //等待
                condition.await();
            }
            i--;
            //完成，通知其他线程
            System.out.println(Thread.currentThread().getName() + i);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}